package br.com.petsis.utilitarios;

import java.io.IOException;
import java.io.InputStream;
import java.util.Date;
import java.util.Properties;

import javax.activation.DataHandler;
import javax.activation.DataSource;
import javax.activation.FileDataSource;
import javax.faces.context.FacesContext;
import javax.mail.Authenticator;
import javax.mail.BodyPart;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.AddressException;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeBodyPart;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMultipart;
import javax.servlet.ServletContext;

public class UtilMail {
	
	public static final String EMAIL_PADRAO_PET = "petitami@petitami.com.br";
	
	private static final String PROPERTY_USERNAME = "mail.username";
	private static final String PROPERTY_SENHA = "mail.password";
	private static final String PROPERTY_FROM = "mail.from";
	
    /** 
    * Método para Enviar e-mail.
    * @param texto
    * @param destinatario
    * @param assunto
    * @return void
    */
   public static void enviarEmail(String texto, String destinatario, String assunto) throws Exception{
	   InputStream input = ((ServletContext) FacesContext.getCurrentInstance().getExternalContext().getContext()).getResourceAsStream("/WEB-INF/classes/mail.properties");  
	   Properties p = new Properties();
	   p.load(input);
	   //p.put("mail.smtp.host", emailHost);
	   //p.put("mail.smtp.auth", "true");
	   
	   Authenticator auth = new SMTPAuthenticator();
	   Session session = Session.getInstance(p, auth);
	   session.setDebug(true);
	   MimeMessage msg = new MimeMessage(session);
		
	   try {  
		    // "de" e "para"!!  
		    msg.setFrom(new InternetAddress(p.getProperty(PROPERTY_FROM)));  
		    msg.setRecipient(Message.RecipientType.TO, new InternetAddress(destinatario));  
		  
		    msg.setSentDate(new Date());
		  
		    msg.setSubject(assunto);  
		  
		    msg.setText(texto);
		    
		//  
	        // This HTML mail have to 2 part, the BODY and the embedded image  
	        //  
	        MimeMultipart multipart = new MimeMultipart("related");  
	  
	        // first part  (the html)  
	        BodyPart messageBodyPart = new MimeBodyPart();  
	        //String htmlText = "<H1>Hello</H1><img src=\"cid:image\">";  
	        messageBodyPart.setContent(texto, "text/html; charset=UTF-8");  
	  
	        // add it  
	        multipart.addBodyPart(messageBodyPart);  
	          
	        // second part (the image)  
	        messageBodyPart = new MimeBodyPart();
	        String caminhoImagens = ((ServletContext) FacesContext.getCurrentInstance().getExternalContext().getContext()).getRealPath("/")+ "img" + java.io.File.separator;;
	        DataSource fds = new FileDataSource  
	          (caminhoImagens+"logo_petitami.jpg");  
	        messageBodyPart.setDataHandler(new DataHandler(fds));  
	        messageBodyPart.setHeader("Content-ID","<image>");  
	  
	        // add it  
	        multipart.addBodyPart(messageBodyPart);  
	  
	        // put everything together  
	        msg.setContent(multipart);  
		  
		    // evniando mensagem (tentando)  
		    Transport.send(msg);  
		}  
		catch (AddressException e) {  
			throw e;
		}  
		catch (MessagingException e) { 
			throw e;
		}  
   }
   
   private static class SMTPAuthenticator extends javax.mail.Authenticator {
       public PasswordAuthentication getPasswordAuthentication() {
    	   try {
    		   InputStream input = ((ServletContext) FacesContext.getCurrentInstance().getExternalContext().getContext()).getResourceAsStream("/WEB-INF/classes/mail.properties");
    		   Properties p = new Properties();
    		   p.load(input);
    		   return new PasswordAuthentication(p.getProperty(PROPERTY_USERNAME), p.getProperty(PROPERTY_SENHA));
    	   } catch (IOException e) {
    		   e.printStackTrace();
    		   return null;
    	   }
           
       }
   }
   
}
